angular.module('CheckWork')

.controller('CheckWork.HomeCtrl', ['$scope', '$state', 'CheckWorkHomeService', 'User','Device', 'imanDialog', '$ionicLoading', 'imanUsbPort', '$ionicModal','DevicePort', function($scope, $state, CheckWorkHomeService, User,Device, imanDialog, $ionicLoading, imanUsbPort, $ionicModal, DevicePort) {
    // var uuid = '00:11:22:33'; // 设备标识
    var Barcode = ''; // 条码标识
    var BarcodeId = 0;
    var bizRecordId = 0;//流水id

    var userId,deviceId,deviceName,workId,workName,WorkLocationId,WorkLocationName = '';
    if(User.get("_id")){
        userId = User.get("_id");//用户id
    }
    if(Device.get("Terminal")){
        deviceId = Device.get("Terminal")._id;
        deviceName = Device.get("Terminal").Name;
    }
    if(Device.get("Work")){
        workId = Device.get("Work")._id;
        workName = Device.get("Work").Name;
    }
    if(Device.get("WorkLocation")){
        WorkLocationId = Device.get("WorkLocation")._id;
        WorkLocationName = Device.get("WorkLocation").Name;
    }
     
    var addFlag = true;//增加还是修改标志位
    //0: 合格 1:不合格 
    var QCStatus = 0;
    //不良位置
    $scope.position = [];
    //存储不良缺陷信息
    var listData = {};
    //存储不良缺陷选中信息
    var listCheck = null;

    var inputStrU = '';//串口传入的条码值
    var submitStatus = false;//是否为提交状态

    $scope.queryStr = '';
    $scope.disableJudge = false;
    //不良缺陷
    $scope.defectList = {};
    $scope.data = {
        work_id: '',
        one: {},
        badRecords: []
    };

    //获取u口返回一维条码的值，扩展枚举编码+枚举值Value
    //BadPosition-0，BadType-0
    function getCodeData(codeData){
           var extendEnum ,value = '';
           extendEnum = codeData.substring(0,codeData.indexOf('-'));
           value = codeData.substring(codeData.indexOf('-')+1);
           // imanDialog.hideLoading();
           if(extendEnum==="BadPosition"){
              // imanDialog.toastBottom("此条码记录缺陷位置信息");
                CheckWorkHomeService.getBadPosition("BadPosition").then(function(data) {
                    imanDialog.hideLoading();
                    if (data != null) {
                        for (var i = 0; i < data.length; i++) {
                            if(data[i].Value+''===value){
                               for (var j = 0; j < $scope.data.badRecords.length; j++) {
                                    if($scope.data.badRecords[j].Status===true){
                                       $scope.data.badRecords[j].BadPosition = data[i].Name;
                                       $scope.data.badRecords[j].BadPositionValue = data[i].Value;
                                       break;
                                    }
                               }
                               break; 
                            }
                            
                        }
                        if(i === data.length){
                           imanDialog.toastBottom("没有此不良位置记录");  
                        }
                        
                    } else {
                        imanDialog.toastBottom("数据为空");
                    }
                }, function(error) {
                    imanDialog.hideLoading();
                    imanDialog.toastBottom(error);
                    
                });
                
           }
           else if(extendEnum==="BadType"){
              // imanDialog.toastBottom("此条码记录缺陷类型信息");
              CheckWorkHomeService.getBadTypeList($scope.data.one.ItemMaster, workId).then(function(data) {
                imanDialog.hideLoading();
                 if (data) {
                    if(data.length===0){
                      imanDialog.toastBottom("可选缺陷信息为空");
                    }
                    else{
                        for (var i = 0; i < data.length; i++) {
                            //此缺陷信息有效
                            if(data[i].Value+'' === value){
                                for (var j = 0; j < $scope.data.badRecords.length; j++) {
                                    if(data[i].Value===$scope.data.badRecords[j].BadTypeValue){
                                       // imanDialog.toastBottom("此缺陷信息已存在"); 
                                       break;
                                    }    
                                }
                                if(j===$scope.data.badRecords.length){
                                    //当前添加的不良类型状态为true，扫码可以修改其不良位置的值，其余置为false
                                    if($scope.data.badRecords.length>0){
                                        for (var a = 0; a < $scope.data.badRecords.length; a++) {
                                            $scope.data.badRecords[a].Status = false;
                                        }
                                    }
                                    $scope.data.badRecords.push({
                                        BadType: data[i].Name,
                                        BadTypeValue: data[i].Value,
                                        BadPosition: "",
                                        BadPositionValue: 0,
                                        Description: "",
                                        Status:true
                                    });
                                }
                                break;
                            }   
                        }
                        if(i===data.length){
                           imanDialog.toastBottom("此缺陷信息无效"); 
                        }
                    }
                    
                 }
                 else{
                     imanDialog.toastBottom("数据为空");
                 }
              },function(error){
                  imanDialog.hideLoading();
                  imanDialog.toastBottom(error);
              });
           }
           

        
    }


    $scope.changeStatus = function(record){
        if($scope.data.badRecords.length>0){
            for (var i = 0; i < $scope.data.badRecords.length; i++) {
                $scope.data.badRecords[i].Status = false;
            }
        }
        record.Status = true;
    };

    $scope.onBadPos = function (defect) {
        imanDialog.showLoading();
        CheckWorkHomeService.getBadPositionList("BadPosition").then(function(data) {
            imanDialog.hideLoading();
            if (data != null) {
                $scope.position = [];
                for(var i in data){
                    $scope.position.push({id:i,name:data[i]});
                }
                imanDialog.showList({
                    title: '请选择碰伤/划伤位置',
                    list: $scope.position,
                    valueField: 'id',
                    displayField: 'name',
                    value: defect.BadPositionValue
                }).then(function (select) {
                    defect.BadPositionValue = select.id;
                    defect.BadPosition = select.name;
                });
            } else {
                imanDialog.toastBottom("数据为空");
            }
        }, function(error) {
            imanDialog.hideLoading();
            imanDialog.toastBottom(error);
            
        });   
    };
    $scope.onDelete = function (one) {
        for (var i = 0; i < $scope.data.badRecords.length; i++) {
            if ($scope.data.badRecords[i].BadTypeValue === one.BadTypeValue) {
                $scope.data.badRecords.splice(i, 1);
                break;
            }
        }
    };


    function getBarcodeDefaultInfo(inputStr) {
        $scope.data.one = {};
        $scope.data.badRecords = [];
        
        imanDialog.showLoading();
        CheckWorkHomeService.getBarcodeData(inputStr).then(function(barcodedata) {
            
            if (barcodedata != null) {
                if(barcodedata.QCStatus===5){
                    $scope.data.one = barcodedata;
                    imanDialog.hideLoading();
                    imanDialog.toastBottom("该单品已经报废");
                    $scope.disableJudge = true;
                }
                else{
                    Barcode = inputStr;
                     //要修改缺陷信息
                    if(workId === barcodedata.Work){
                       if(!submitStatus){
                          imanDialog.toastBottom("请修改缺陷信息");
                       }
                       addFlag = false; 
                       BarcodeId = barcodedata._id;
                       CheckWorkHomeService.getBarcodeDefectData(BarcodeId,workId).then(function(data){
                         imanDialog.hideLoading();
                         $scope.data.one = barcodedata;
                         $scope.data.badRecords = data.defectDatas;
                         bizRecordId = data.bizRecordID;
                         if($scope.data.badRecords.length>0){
                            $scope.data.badRecords[$scope.data.badRecords.length-1].Status = true; 
                         }      
                       },function(eror){
                         imanDialog.hideLoading();
                       });
                    }
                    //要增加缺陷信息
                    else{
                       if(!submitStatus){
                          imanDialog.toastBottom("请增加缺陷信息");
                       }
                       addFlag = true; 
                       imanDialog.hideLoading();
                       $scope.data.one = barcodedata;
                    }
                }
                
                
            } else {
                imanDialog.hideLoading();
                imanDialog.toastBottom("单品数据为空");
            }
            
        }, function(error) {
            imanDialog.hideLoading();
            if(error){
                imanDialog.toastBottom(error.message);
            }
           
        });

    }

    $ionicModal.fromTemplateUrl(u9ImHd.getFullPath('tpls/defectModal.html', 'CheckWork'), {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.modal = modal;
    });
    $scope.openModal = function() {
        
        imanDialog.showLoading();
        CheckWorkHomeService.getBadTypeList($scope.data.one.ItemMaster, workId).then(function(data) {
            imanDialog.hideLoading();
            $scope.defectList = {};
            var pinyin = '';
            var pinyinTop = '';
            var name = '';
            var value = 0;
            if (data != null) {
                if(data.length>0){
                    $scope.modal.show();
                    for (var i = 0; i < data.length; i++) {
                        name = data[i].Name;
                        value = data[i].Value;
                        pinyin = makePy(name)[0].toLowerCase();
                        pinyinTop = pinyin.charAt(0).toUpperCase();
                        
                        if ($scope.defectList[pinyinTop]) {
                            $scope.defectList[pinyinTop].push({name:name,value:value,pinyin:pinyin,check:false});
                        } else {
                            $scope.defectList[pinyinTop] = [{name:name,value:value,pinyin:pinyin,check:false}];
                        }   
                    }
                    var temp = {};
                    for (var c = 65; c < 91; c++) {
                        for(var d in $scope.defectList){
                            if(d.charCodeAt(0)===c){
                              temp[d] = $scope.defectList[d];
                              break;
                            }
                        }
                    }

                    $scope.defectList = temp;

                    listData = $scope.defectList;

                    // //增加
                    // if(addFlag){
                    //     if(listCheck){
                    //         for (var k in listCheck) {      
                    //            var pinyinTopList = listCheck[k];
                    //            for (var j = 0; j < pinyinTopList.length; j++) {
                    //                for (var a in listData) {      
                    //                    var pinyinList = listData[a];
                    //                    for (var b = 0; b < pinyinList.length; b++) {
                    //                        if(pinyinTopList[j].value === pinyinList[b].value){
                    //                           listData[a][b].check = listCheck[k][j].check;
                    //                        }
                    //                    }
                    //                 }
                    //             }
                    //         }
                    //     }
                    //     else{
                    //         listCheck = listData;
                    //     }
                    // }
                    //编辑 根据主页已选的缺陷信息 更新弹出页缺陷列表的选择情况
                    // else{
                       for (var p = 0; p < $scope.data.badRecords.length; p++) {
                           for (var m in listData) {      
                               var pinyinList2 = listData[m];
                               for (var n = 0; n < pinyinList2.length; n++) {
                                   if($scope.data.badRecords[p].BadTypeValue === pinyinList2[n].value){
                                      listData[m][n].check = true;
                                   }
                               }
                           }
                       }
                       listCheck = listData;  
                    // }
                }
                else{
                    imanDialog.toastBottom("可选缺陷信息为空");
                }   
            } else {
                imanDialog.toastBottom("可选缺陷信息为空");
            }
        
        }, function(error) {
            imanDialog.hideLoading();
            $scope.data = {};
        });

    };
    $scope.closeModal = function() {
        $scope.modal.hide();       
    };

    $scope.submitData = function(qcStatus) {
        submitStatus = true;
        imanDialog.showLoading();
        if(addFlag){
            // QCStatus = $scope.data.badRecords.length>0 ? 1 : 0;
            
            CheckWorkHomeService.submitBadData(Barcode,$scope.data.one._id,
                $scope.data.one.ItemMaster,deviceId,deviceName,workId,workName,
                WorkLocationId,WorkLocationName,userId,qcStatus,$scope.data.one.QCStatus,
                $scope.data.badRecords,$scope.data.one.ReworkQty).then(function(data) {
                imanDialog.hideLoading();
                if (data) {
                    imanDialog.toastBottom("不良品检验成功");
                } else {
                    imanDialog.toastBottom("不良品检验失败");
                }
                getBarcodeDefaultInfo(inputStrU);
            }, function(res) {
                imanDialog.hideLoading();
            });
        }
        else{
            CheckWorkHomeService.updateBadData(bizRecordId,BarcodeId,Barcode,userId,
                $scope.data.badRecords,qcStatus,$scope.data.one.QCStatus,
                $scope.data.one.ReworkQty,workId,$scope.data.one.ItemMaster).then(function(data){
                imanDialog.hideLoading();
                if (data) {
                    imanDialog.toastBottom("更新不良品检验数据成功");
                } else {
                    imanDialog.toastBottom("更新不良品检验数据失败");
                }
                getBarcodeDefaultInfo(inputStrU);
            },function(error){
                imanDialog.hideLoading();
            });
        }
        
    };
    

    // 保存选中记录
    $scope.checkChange = function(one) {
        for (var a in listCheck) {      
           var pinyinList = listCheck[a];
           for (var b = 0; b < pinyinList.length; b++) {
               if(one.value === pinyinList[b].value){
                  listCheck[a][b].check = one.check;
               }
           }
        }
        
        if(one.check){
            //当前添加的不良类型状态为true，扫码可以修改其不良位置的值，其余置为false
            if($scope.data.badRecords.length>0){
                for (var j = 0; j < $scope.data.badRecords.length; j++) {
                    $scope.data.badRecords[j].Status = false;
                }
            }
            $scope.data.badRecords.push({
                BadType: one.name,
                BadTypeValue: one.value,
                BadPosition: "",
                BadPositionValue: 0,
                Description: "",
                Status:true
            });
        }
        else{
            for (var i = 0; i < $scope.data.badRecords.length; i++) {
                if ($scope.data.badRecords[i].BadTypeValue === one.value) {
                    $scope.data.badRecords.splice(i, 1);
                    break;
                }
            }
        }      
    };
    // //删除缺陷类型
    // $scope.deleteDeft = function(one) {
    //     for (var i = 0; i < $scope.data.badRecords.length; i++) {
    //         if ($scope.data.badRecords[i].BadTypeValue === one.value) {
    //             $scope.data.badRecords.splice(i, 1);
    //             break;
    //         }
    //     }
    // };
    
    $scope.search = function(query) {
        if (query === "") {
            $scope.defectList = listCheck;
        }
        if (query !== "") {
            var nName;
            var nPinyin;
            $scope.defectList = {};

            for (var i in listData) {      
                var pinyinTopList = listData[i];
                for (var j = 0; j < pinyinTopList.length; j++) {
                    var item = pinyinTopList[j];
                    var pinyin = item.pinyin;
                    var name = item.name;
                    nName = find(query, name);
                    nPinyin = find(query, pinyin);
                    if (nName >= 0 || nPinyin >= 0) {
                        if ($scope.defectList[i]) {
                            $scope.defectList[i].push({name:item.name,value:item.value,pinyin:item.pinyin,check:item.check});
                        } else {
                            $scope.defectList[i] = [{name:item.name,value:item.value,pinyin:item.pinyin,check:item.check}];
                        }
                    }
                    
                }  
            }
            
        }
        
    };

    function find(sFind, sObj) {
        var nSize = sFind.length;
        var nLen = sObj.length;
        var sCompare;

        if (nSize <= nLen) {
            for (var i = 0; i <= nLen - nSize + 1; i++) {
                sCompare = sObj.substring(i, i + nSize);
                if (sCompare === sFind) {
                    return i;
                }
            }
        }
        return -1;
    }

    $scope.$on('$ionicView.beforeLeave', function () {
        imanUsbPort.stop();
        DevicePort.close();
    });
    $scope.$on('$ionicView.afterEnter', function () {
        imanUsbPort.start();
        DevicePort.open({
            device: 0,
            baudrate: 115200,
            parseFn: true
        }).then(function () {
            // imanDialog.toastBottom("成功");
        }, function (err) {
            imanDialog.toastBottom(err);
        });
    });
    $scope.$on('devicePort.DataReceived', function (e, barcode) {
        getBarcodeDefaultInfo(barcode);
        inputStrU = barcode;
    });


    // $scope.$on('$ionicView.afterEnter', function() {
    //     imanUsbPort.start();
    // });
    // $scope.$on('$ionicView.beforeLeave', function() {
    //     imanUsbPort.stop();
    // });
    $scope.$on('imanUsbPort.input', function(e, inputStr) {
        getCodeData(inputStr);        
    });
        //当我们用到模型时，清除它！
      $scope.$on('$destroy', function() {
        $scope.modal.remove();
      });
      // 当隐藏的模型时执行动作
      $scope.$on('modal.hide', function() {
        // 执行动作
        $scope.queryStr = '';
      });
}]);